"use client"
import * as React from "react";
import {Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Fab, TextField} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import Button from "@mui/material/Button";
import { revalidateTag } from "next/cache";

export function Form(data) {
    const [open, setOpen] = React.useState(false);

    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    const handleAdd = () => {
        const postData = {};

        for (let key in data.list) {
            postData[key] = document.getElementById(key).value;
        }

        // Create an object with the data
        fetch('/api/' + data.type + '/increase', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData),
        })
            .then(response => response.json())
            .then(result => {
                console.log('Success:', result);
                setOpen(false); // Close the dialog after successful request
            })
            .catch(error => {
                console.error('Error:', error);
            });
        setOpen(false);
        revalidateTag(api_type)
    };
    return (
        <div>
            <Fab aria-label="add" onClick={handleClickOpen}>
                <AddIcon/>
            </Fab>

            <Dialog open={open} onClose={handleClose}>
                <DialogTitle>新增</DialogTitle>
                <DialogContent>
                    <DialogContentText>
                        新增信息
                    </DialogContentText>
                    {Object.keys(data.list).map((key) => (
                        <TextField
                            key={key}
                            margin="dense"
                            id={key}
                            label={data.list[key]['name']}
                            type={data.list[key]['type']}
                            fullWidth
                            variant="standard"
                        />
                    ))}
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleClose}>取消</Button>
                    <Button onClick={handleAdd}>确认</Button>
                </DialogActions>
            </Dialog>
        </div>
    )
}